﻿using CloudStorageLight.Core;
using CloudStorageLight.Core.Web;
using Microsoft.Azure.ActiveDirectory.GraphClient;
using Microsoft.Azure.ActiveDirectory.GraphClient.Extensions;
using Microsoft.IdentityModel.Claims;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Security.Principal;
using System.Threading.Tasks;
using System.Web;

namespace CloudStorageLight.SharePointWeb.Models
{
    public class AppBlobUser : BlobUser
    {
        static IPrincipal CreatePrincipal(IPrincipal user)
        {
            if (user.Identity.IsAuthenticated)
            {
                var cloudAccount = BlobService.GetCurrentCloudAccount();
                if (cloudAccount != null && cloudAccount.AzureAdMode)
                {
                    try
                    {
                        var authority = cloudAccount.Authority;
                        var cloudStorageLightAppKey = cloudAccount.CloudStorageLightAppKey;
                        var cloudStorageLightClientId = cloudAccount.CloudStorageLightClientId;
                        var tenantId = cloudAccount.TenantId;                        
                        //user = AzureAdUtil.CreatePrincipal(authority, cloudStorageLightClientId, cloudStorageLightAppKey, tenantId, user.Identity.Name);
                        var group = AzureAdUtil.ListGroupOfMember(authority, cloudStorageLightClientId, cloudStorageLightAppKey, tenantId, user.Identity.Name);
                        group = group ?? new string[] { };
                        user = new GenericPrincipal(new GenericIdentity(user.Identity.Name), group.Select(x=>x.ToLower()).ToArray());
                    }
                    catch (Exception ex)
                    {
                        LogError(cloudAccount, ex.ToString());
                        Debug.WriteLine(ex.ToString());
                        return user;
                    }

                }
            }
            return user;
        }

        static void LogError(CloudAccount account, string message)
        {
            if (HttpContext.Current == null) return;
            try
            {
                var svc = new LogService(SystemSettings.Instance.BlobStorage);
                svc.EntryLog(HttpContext.Current.User.Identity.Name, account.AccountName, "Error", HttpContext.Current.Request.Url.PathAndQuery, message, HttpContext.Current.Application);
            }
            catch
            {
            }
        }

        static void LogInfo(CloudAccount account, string message)
        {
            try
            {
                var svc = new LogService(SystemSettings.Instance.BlobStorage);
                svc.EntryLog(HttpContext.Current.User.Identity.Name, account.AccountName, "Info", HttpContext.Current.Request.Url.PathAndQuery, message, HttpContext.Current.Application);
            }
            catch
            {
            }
        }


        public AppBlobUser(IPrincipal user)
            : this(CreatePrincipal(user), BlobService.GetCurrentCloudAccount())
        {
        }

        public AppBlobUser(IPrincipal user, CloudAccount cloudAccount)
            : base(CreatePrincipal(user))
        {
            if (cloudAccount != null)
            {
                IsAdmin = cloudAccount.GetAdministrators().Any(x => string.Equals(x, this.Name, StringComparison.InvariantCultureIgnoreCase));
                if (string.Equals(cloudAccount.EMailAddress, this.Name, StringComparison.InvariantCultureIgnoreCase)) IsAdmin = true;
            }
        }
    }
}